import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-24
 * Time: 20:16
 */

class Student{
    public String studentId;
    public String classId;
}
@WebServlet("/postParameter")
public class postParameter extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // post请求的body中获取出json格式的数据
//        int length = req.getContentLength();
//        byte[] buffer = new byte[length];//存储body
//        InputStream inputStream = req.getInputStream();
//        inputStream.read(buffer);
//        //将这个body打印出来
//        String body = new String(buffer);
//        System.out.println(body);
//        resp.getWriter().write(body);

        //使用jackson涉及核心对象
        ObjectMapper objectMapper = new ObjectMapper();
        //readvalue就是把一个json类型的格式
        // 获取到body中的数据组织成map格式，再根据类对象遍历，填充字段返回一个类对象
        //如果没有对应的字段，返回一个500错误
        Student student = objectMapper.readValue(req.getInputStream(),Student.class);
        System.out.println(student.studentId+"  "+student.classId);
        resp.getWriter().write(student.studentId+"  "+student.classId);
    }
}
